const express = require('express');
const router = express.Router();
const request = require('request');
const jsSHA = require('jssha');
//addid信息
const appid = 'wxbe056cf67e0004f5';
const secret = 'bfa04bc8d80a839b231d7b84100e0717';

// 微信的access_token
const tokenUrl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' + appid + '&secret=' + secret;

function requestPromise(config, acceptStatusCode = (statusCode) => statusCode === 200) {
  let promiseCallbackAF;
  return new Promise(promiseCallbackAF = (fulfill, reject) => {
    let responseCallbackAF;
    request(config, responseCallbackAF = (err, response) => {
      if (err) {
        return reject(err);
      }
      if (!acceptStatusCode(response.statusCode)) {
        return reject('Response status code is not accepted.');
      }
      return fulfill(response);
    });
  });
}

let createNonceStr = function () {
  return Math.random().toString(36).substr(2, 15);
};

let createTimestamp = function () {
  return parseInt(new Date().getTime() / 1000)+ '';
};

let raw = function (args) {
  let keys = Object.keys(args);
  keys = keys.sort();
  let newArgs = {};
  keys.forEach(function (key) {
    newArgs[key.toLowerCase()] = args[key];
  });
  let string = '';
  for (let k in newArgs) {
    string += '&' + k + '=' + newArgs[k];
  }
  string = string.substr(1);
  return string;
};

let sign = function (jsapi_ticket, url) {
  let ret = {
    jsapi_ticket: jsapi_ticket,
    nonceStr: createNonceStr(),
    timestamp: createTimestamp(),
    url: url
  };
  let string = raw(ret),
    shaObj = new jsSHA(string, 'TEXT');
  ret.signature = shaObj.getHash('SHA-1', 'HEX');

  return ret;
};
/**
 * @param jsapi_ticket {string}
 * @param url {url} 请求的当前前端url,如何是根目录需要加/
 */

/* GET home page. */
router.get('/', function (req, res, next) {
  let url = req.query.url;
  (async () => {
    try {
      // 1.异步请求获取access_token
      let tokenResponse = await requestPromise({url: tokenUrl});
      let tokenResult = JSON.parse(tokenResponse.body);
      let accessToken = tokenResult.access_token;

      // 2.异步请求获取jsapi_ticket
      const ticketUrl = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=' + accessToken + '&type=jsapi';
      let ticketResponse = await requestPromise({url: ticketUrl});
      let ticketResult = JSON.parse(ticketResponse.body);
      let ticket = ticketResult.ticket;

      // 3.返回sign_nature
      let sign1 = sign(ticket, url);
      sign1.appid=appid;
      res.send(sign1);

    } catch (e) {
      console.log(e);
    }
  })();
});

module.exports = router;
